from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .ser import *
from django.core.paginator import Paginator


# Create your views here.

# 新闻表的操作
class Journalism_views(APIView):
    def post(self, request):
        # 先获取所有字段
        show = JournalismSer(data=request.data)
        # 判断字段存不存在
        if show.is_valid():
            # 保存
            show.save()
            return Response({'code': 200})
        else:
            return Response({'code': 400})

    def get(self, request):
        # 获取前端传过来的
        cpage = request.GET.get('page')
        # 获取他的所有数据
        show = Journalism.objects.all()
        # 它分为多少页
        pageall = Paginator(show, 2)
        # 分页展示
        date = pageall.page(cpage)
        # 序列化
        ser = JournalismSer(date, many=True)
        return Response({'code': 200, 'list': ser.data, 'num': pageall.num_pages})


class Advertising_views(APIView):
    def post(self, request):
        # 先获取所有字段
        show = AdvertisingSer(data=request.data)
        # 判断字段存不存在
        if show.is_valid():
            # 保存
            show.save()
            return Response({'code': 200})
        else:
            return Response({'code': 400})

    def get(self, request):
        # 先获取分页
        cpage = request.GET.get('page')
        # 获取所有数据
        show = Advertising.objects.all()
        # 要分多少页
        pageall = Paginator(show, 2)
        # 展示分页的数据
        date = pageall.page(cpage)
        # 序列化
        ser = AdvertisingSer(date, many=True)
        return Response({'code': 200, 'list': ser.data, 'num': pageall.num_pages})
